var express = require('express'),
  router = express.Router(),
  bodyParser = require('body-parser'),
  multiparty = require('multiparty'),
  util = require('util'),
  compressing = require('compressing');
basic = require('../../basicmodule/basic.js'),
  fs = require('fs');

var utils = require('../tool/Utils.js')

const UPLOADPATH = basic.getFilePath('freedom' + utils.format + 'upload' + utils.format);


module.exports = function (app) {
  app.use('/', router);
};

router.post('/upload.html', function (req, res) {

  // 解析一个文件上传
  var form = new multiparty.Form({uploadDir: UPLOADPATH, maxFilesSize: 100 * 1024 * 1024, encoding: 'utf-8'});

  //form.maxFields = 1000;  设置所以文件的大小总和
  form.parse(req, function (err, fields, files) {
    if (err) {
      console.log(err);
    } else {
      var fileName = (files.file[0]).originalFilename;

      if (fileName != '') {
        var filePath = (files.file[0]).path;
        var newFilePath = UPLOADPATH + fileName;
        //同步重命名文件名
        fs.renameSync(filePath, newFilePath);

        if (fileName.lastIndexOf('.zip') > 0) {
          // 包含zip文件
          // 解压缩

          var tempath = newFilePath.replace('.zip', '');
          //先看有没有已经解压的一样的文件o
          if (fs.existsSync(tempath)) {
            utils.deleteall(tempath);
          }

          compressing.zip.uncompress(newFilePath, UPLOADPATH)
            .then(() => {
              console.log('success');
              fs.unlink(newFilePath, err => {
                console.log(err)
                res.redirect('/index.html');
              });
            })
            .catch(err => {
              console.error(err);
              res.redirect('/index.html');
            });
        }else{
          res.redirect('/index.html');
        }

      }
    }
  });
});





